<template>
  <div :class="$style.wrap" :style="{display:isEdit?'inline-block':'block'}">
    <div :class="$style.button">
      <Button :type="type" @click="visible=true">{{ title }}</Button>
    </div>
    <el-dialog :visible.sync="visible" :title="title" :close-on-click-modal="false" @open="initFormData" @close="resetForm">
      <el-tabs v-model="tabName" @tab-click="tabClickHandle">
        <el-tab-pane label="选择题" name="0">
          <FormContainer v-if="tabName==='0'" :column="1">
            <el-form ref="form" :model="formData" :rules="formRules" label-width="40px">
              <!-- <el-form-item prop="questionType" label="题型">
                <el-select v-model="formData.questionType" placeholder="请选择" filterable :class="$style.no100">
                  <el-option value="0" label="单选"></el-option>
                  <el-option value="1" label="多选"></el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item prop="questionTitle">
                <el-input v-model="formData.questionTitle" type="textarea" :autosize="{minRows:1}" placeholder="请输入题目" clearable></el-input>
              </el-form-item>
              <el-form-item v-if="formData.questionOptionDTOList.length>0 && visible" prop="questionOptionDTOList">
                <AnswerSelect v-for="(a,i) in formData.questionOptionDTOList" :key="i" v-model="formData.questionOptionDTOList[i]" :index="i" @on-remove="removeAnswerHandle"></AnswerSelect>
              </el-form-item>
              <el-form-item>
                <div :class="$style.addIcon" @click.stop="addAnswer">
                  <svg-icon icon-class="tianjiaxinjian"></svg-icon>
                  <span>添加选项</span>
                </div>
              </el-form-item>
            </el-form>
          </FormContainer>
        </el-tab-pane>
        <el-tab-pane label="填空题" name="2">
          <FormContainer v-if="tabName==='2'" :column="1">
            <el-form ref="form" :model="formData" :rules="formRules" label-width="0px">
              <el-form-item prop="questionTitle">
                <el-input v-model="formData.questionTitle" type="textarea" :autosize="{minRows:1}" placeholder="请输入题目" clearable></el-input>
              </el-form-item>
              <el-form-item v-if="formData.questionOptionDTOList.length>0 && visible" prop="questionOptionDTOList">
                <AnswerFill v-for="(a,i) in formData.questionOptionDTOList" :key="i" v-model="formData.questionOptionDTOList[i]" :index="i" @on-remove="removeAnswerHandle"></AnswerFill>
              </el-form-item>
              <!-- <el-form-item>
                <div :class="$style.addIcon" @click.stop="addAnswer">
                  <svg-icon icon-class="tianjiaxinjian"></svg-icon>
                  <span>添加输入框</span>
                </div>
              </el-form-item> -->
            </el-form>
          </FormContainer>
        </el-tab-pane>
      </el-tabs>
      <div class="button-container" style="padding-top:0">
        <Button type="primary" @click="cancelHandle">取消</Button>
        <Button type="primary" @click="saveHandle">{{ !isEdit?'保存并返回':'保存' }}</Button>
        <Button v-if="!isEdit" type="primary" @click="saveHandle('add')">保存并添加</Button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { questionObj, optionObj } from '../../common'
import FormContainer from '@/components/FormContainer'
import AnswerSelect from './answerSelect'
import AnswerFill from './answerFill'
import { deepCopy } from '@/utils'
import { questionnaireItemAdd, questionnaireItemUpdate } from '@/api/questionnaire'
export default {
  name: 'Question',
  components: {
    FormContainer,
    AnswerSelect,
    AnswerFill
  },
  props: {
    question: {
      type: Object,
      default: () => ({})
    },
    index: {
      type: Number,
      default: undefined
    },
    type: {
      type: String,
      default: 'primary'
    },
    title: {
      type: String,
      default: '添加题目'
    },
    questionnaireId: {
      type: String,
      default: ''
    },
    chapterId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      tabName: '0',
      formData: {
        questionTitle: '',
        questionType: '0', // 题目类型：0单选1多选2填空3章节
        scoreType: 0, // 得分类型：0选中扣分1选中得分
        isScore: 0, // 是否评分题：0否 1是
        questionOptionDTOList: [],
        displaySerialNumber: 0
      },
      formRules: {
        questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
        questionTitle: [{ required: true, message: '请输入题目', trigger: 'change' }]
      },
      // 要删除的选项
      deleteOptionDTOList: []
    }
  },
  computed: {
    isEdit() {
      return Object.keys(this.question).length > 0
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    initFormData() {
      this.formData = questionObj(this.index)
      this.tabName = '0'
      if (this.isEdit) {
        for (const k of Object.keys(this.formData)) {
          this.$set(this.formData, k, deepCopy(this.question[k]))
          if (k === 'questionType' && this.question[k] !== undefined && this.question[k] !== null) {
            this.$set(this.formData, k, this.question[k].toString())
          }
        }
        if (this.formData.questionType === '2') {
          this.tabName = '2'
        } else {
          this.tabName = '0'
        }
      }
      if (this.$refs.form) {
        let t = this.$refs.form
        if (!(t instanceof Array)) {
          t = [this.$refs.form]
        }
        for (const e of t) {
          this.$nextTick(e.clearValidate)
        }
      }
    },
    resetForm() {
      // this.$refs.form.resetFields()
    },
    // 标签切换
    tabClickHandle(tab) {
      this.$set(this.formData, 'questionType', tab.name)
      this.$set(this.formData, 'questionOptionDTOList', [])
      this.addAnswer()
    },
    // 增加答案
    addAnswer() {
      this.formData.questionOptionDTOList.push(optionObj(this.question.id))
    },
    // 删除答案
    removeAnswerHandle(index) {
      const item = this.formData.questionOptionDTOList.splice(index, 1)
      if (item[0].id) {
        this.deleteOptionDTOList.push(...item)
      }
    },
    cancelHandle() {
      this.visible = false
    },
    saveHandle(type) {
      this.$refs.form.validate().then(() => {
        if (this.formData.questionOptionDTOList.length <= 0) {
          this.$message.warning('请添加问题项！')
          return
        }
        const data = deepCopy(this.formData)
        let ajax = questionnaireItemAdd
        // 处理questionType
        if (typeof data.questionType === 'string') {
          data.questionType = parseInt(data.questionType)
        }
        if (this.isEdit) {
          ajax = questionnaireItemUpdate
          data.id = this.question.id
          data.addOrUpdateOptionDTOList = data.questionOptionDTOList
          data.deleteOptionDTOList = this.deleteOptionDTOList
        }
        data.questionnaireId = this.questionnaireId
        data.chapterId = this.chapterId
        ajax(data).then(res => {
          this.$emit('on-refresh')
          if (type === undefined) {
            this.visible = false
          } else {
            this.initFormData()
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" module>
.wrap{
  .button{
    text-align: center;
    padding: 0 10px;
  }
  .no100{
    width: auto !important;
  }
  .addIcon{
    display: inline-block;
    cursor: pointer;
    font-size: 14px;
    font-weight: normal;
  }
}
</style>
